GetKeyState (user32)
Last changed: -46.250.60.45

.
Summary
The GetKeyState function retrieves the status of the specified virtual key. The status specifies whether the key is up, down, or toggled (on, off—alternating each time the key is pressed).

C# Signature:

[DllImport("user32.dll")]
static extern short GetKeyState(int nVirtKey);

VB Signature:

<DllImport("user32.dll")> _
Public Function GetKeyState(ByVal nVirtKey As Integer) As Integer
End Function

User-Defined Types:

None.

Notes:

Here are some sample values for nVirtKey:

const int VK_SHIFT = 0x10;   // Use Keys.ShiftKey
const int VK_CONTROL = 0x11; // Use Keys.ControlKey
const int VK_MENU = 0x12;    // Use Keys.Menu

Tips & Tricks:

'Use the System.Windows.Forms.Keys enumeration instead of VK codes,
'but make sure you use the right one! (Keys.ShiftKey not Keys.Shift, etc.)

Sample VB Code:

Imports System.Windows.Forms

Public Function IsKeyDown(ByVal keys As Keys) As Boolean
    Return (GetKeyState(CInt(keys)) And &H8000) = &H8000
End Function

Public Function IsKeyOn(ByVal keys As Keys) As Boolean
     Return (GetKeyState(CInt(keys)) And &H1) = &H1
End Function

Sample C# Code:

using System.Windows.Forms;

public static bool IsKeyLocked(Keys keyVal) {
     switch( keyVal ) {
    case Keys.NumLock :
    case Keys.Capital :
    case Keys.Scroll :
    case Keys.Insert :
        return (GetKeyState((int)keyVal) & 0x8001) != 0;
     }
     return false;
}

public static bool IsKeyPressed(Keys keyVal) {
     return GetKeyState((int)keyVal) < 0;
}

// --- Added by Kasper ---

    /// <summary>
    /// This method tests whether a key is down or not.
    /// </summary>
    /// <param name="k">The key to test.</param>
    /// <returns>True if the keys is down.</returns>
    public static bool IsKeyDown(System.Windows.Forms.Keys k)
    {
        short state = GetKeyState((int)k);
        if((state & 0x8000) == 0x8000) //It's down
            return true;
        return false;
    }
    /// <summary>
    /// This method tests whether a key is on or not.
    /// </summary>
    /// <param name="k">The key to test.</param>
    /// <returns>True if the keys is on.</returns>
    public static bool IsKeyOn(System.Windows.Forms.Keys k)
    {
        short state = GetKeyState((int)k);
        if((state & 0x0001) == 0x0001) //It's on
            return true;
        return false;
    }

Alternative Managed API:

Do you know one? Please contribute it!

Documentation
GetKeyState on MSDN